
#include "kb.h"                 // keybaord event type 
#include "touch_algorithm.h"    // touch event type 
#include "custom_event.h"
#include "gui.h"                // GUI header

#include "views.h"              // include all views 
#include "log.h"                // LOG file 
#define LOG     LOG_INFO0

#include "xapp_config.h"
#include "xapp_clock.h"


#if USER_CHECK_ENABLED(TEMPERATURE)
#include "xapp_temperature.h"
#endif 

#include "views_util.h"
#include "xapp_localize.h"
#include "xapp_hrs.h"
enum tagTEMP
{
    tagTEMPDragStart,
    tagTEMPToLeft,
    tagTEMPToRight,
    tagTEMPBack,
};

enum flagHeartrate
{
    flagPaintAll,
    flagPaintIcon,
    flagPaintValue,
};

// declare function 
GUI_VIEW_FUNC_DECLARE_ALL;
static void local_view_event_handler( uint32_t tag );
static uint8_t had_report_touch_state=false;
static float temp_value=0;
static uint8_t temp_realtime_value[5];
//static uint8_t temp_lasttime_value[5];
const static ui_widgets_type_t wglHeartrate/*1. modify name*/[] = 
{
    // background 
    [0] = uiPictureBox( IMG_Health_BG_360_360_01, 0, 0, 0, GUI_LCD_RES_H, GUI_LCD_RES_V ),
    // temperature ani icon
    [1] = uiDigitalOverlay( IMG_Health_Temperature_Icon_098_098_02,     132, 36, 98, 98, COLOR_BLACK ),
    // realtime value
    [2] = uiNumberlistWithBuffer( 0, SIZE_SCALE(104), SIZE_SCALE(240), SIZE_SCALE(52), COLOR_BLACK, COLOR_WHITE, ALIGN_MIDDLE_CENTOR, FILL_NONE, ENCODING_ASCII, FONT_ASCII_1_40_52, "%d.%d", temp_realtime_value, 5 ),
    // empty value
    [3] = uiLabel( SIZE_SCALE(0)  , SIZE_SCALE(104), SIZE_SCALE(240), SIZE_SCALE(52), COLOR_BLACK, COLOR_YELLOW, ALIGN_MIDDLE_CENTOR, FILL_NONE, ENCODING_ASCII, FONT_ASCII_1_40_52, "-- ", 3),
    
    // temperature unit
    [4] = uiDigitalOverlay( IMG_Health_Temperature_Unit_038_034_01, 228,186, 38, 34, COLOR_BLUE ),
    // wear tip index = 0
    [5] = uiDigitalOverlay( IMG_Health_Wear_Tip_136_084_03, 112, 254, 136, 84, COLOR_BLUE ),
    
//    // unit
//    [4] = uiPictureBoxOverlay( IMG_Health_Temperature_Unit_029_027_01, 0, SIZE_SCALE(160), SIZE_SCALE(121), 29, 27, COLOR_BLACK ),

//    // 最近一次测量结果（显示）
//    [5] = uiTextbox( 0, SIZE_SCALE(160), GUI_LCD_RES_H, SIZE_SCALE(60), COLOR_BLACK, COLOR_WHITE, ALIGN_MIDDLE_CENTOR, FILL_NONE, ENCODING_UNICODE, FONT_UNICODE_20_29 ),
};

const static ui_refresh_part_t partTEMP[] = 
{
    [0] = xRECTANGLE(((SIZE_SCALE(90)-3)/4)*4, ((SIZE_SCALE(29)-3)/4)*4,  ((SIZE_SCALE(60)+3+4)/4)*4,  ((SIZE_SCALE(60)+3+4)/4)*4), // icon animation
    [1] = xRECTANGLE(SIZE_SCALE(0) , SIZE_SCALE(104), SIZE_SCALE(240), SIZE_SCALE(52) ), // value update
};


GUI_VIEW_DEF( viewApp_Temperature ) = 
{
    // name 
    .name = "App+Temperature",
    
    // init 
    .init = initialize,
    .display_func = display_callback_func,
    .refresh_func_check = display_refresh_func,
    .destroy_func = on_destroy_func,
    .set_parent_func = on_set_parent_func, 
    
    // input 
    .on_touch = on_touch,
    .on_button = on_button,
    .on_event_update = on_event_update,     
    
    .pWidgetlist =  (ui_widgets_type_t*)wglHeartrate /* 3. fill with widgets list name */,
    .widget_cnt = WIDGET_COUNT( wglHeartrate ), /* 3. fill with widgets list name */

    .flag = GUI_VIEW_FLAG_FUNC | GUI_VIEW_FLAG_ALIVE_DELAY
};


/* 当前view初始化
// 需要指定前使用的控件组
// 自动更新间隔，不使用自动更新间隔则interval = 0

*/
static void initialize(gui_menu_t * menu, void* pvParameter)
{
    menu->interval = 0;
    menu->lifetime = 60 * 1000; // 60seconds max 

    views_animate_set_count( 2 );    
    had_report_touch_state=false;
    temp_value=0;
}
static void on_set_parent_func(gui_menu_t * menu, const gui_view_t * parent)
{
    p_this_parent = parent;
}
/* 销毁函数
// 在销毁前处理当前信息，比如不允许销毁时，将当前界面状态保存为background。
// true:  允许销毁
// false: 不允许自动销毁，则GUI只关闭当前显示，输入事件仍由当前view进行处理。
          那么view判断当前状态为background时，作出对应background下的按键、触摸等事件反馈
*/
static uint32_t on_destroy_func(gui_menu_t * menu)
{
    xapp_hrs_send_msg_stop( HRS_MODE_DET | HRS_START_SRC_AUTO );
    return GUI_DESTROY_RET_DEFAULT; 
}

/* 显示回调
   重新指定参数, 用来获取当前界面的控件组
   ** 当前界面有多个控件组时，应该有条件确定使用哪一组控件组 ** 
*/
static void display_callback_func(gui_menu_t * menu)
{
    ui_property_t prop;
    ui_widgets_type_t * widgets = menu->widgets;

    if(  IS_REQ_SRC_CREATE( menu->source ) )
    {        
        PROP_UPDATE_NULL_AT_NO( 3 );
//        PROP_UPDATE_NULL_AT_NO( 4 );
        
        if( IS_REQ_SRC_CREATE_SINGLE( menu->source ) )
        {
            #if USER_CHECK_ENABLED(TEMPERATURE)
            const xapp_temperature_desc_t* p_temp_desx = xapp_temperature_get_desc();

            // 创建界面时， 开始测量
            if( p_temp_desx->mounted )
            {
                xapp_temperature_start_by( TEMP_START_SRC_VIEW );

//                gui_part_t gui_part = GUI_PART_CONFIG( partTEMP, 500);
//                gui_part_create( &gui_part );
            }
            else 
            {
                gui_core_interval_update(menu, 3000);
                gui_core_lifetime_update( menu, 10000 );
            }

            gui_part_t gui_part = GUI_PART_CONFIG( partTEMP, 500);
            gui_part_create( &gui_part );
            
            //zhao
            //if(!xapp_hrs_is_wear())
            {
                xapp_hrs_send_msg_start( HRS_MODE_DET | HRS_START_SRC_AUTO );
            }

            #endif 
        }

        FLAG_ALL();
    }

    if( menu->source == GUI_VIEW_REQ_SRC_UPDATE_PART )
    {
        FLAG_SETB( flagPaintIcon );
    }
//    if( menu->source == GUI_VIEW_REQ_SRC_UPDATE_EVENT )
    {
        FLAG_SETB( flagPaintValue );
    }

    if( FLAG_GETB(flagPaintIcon) )
    {
        prop.digital.idx = views_animate_get_idx_by_step();
        gui_widget_update_prop( &widgets[1], &prop );
    }

    if( FLAG_GETB( flagPaintValue) )
    {
        #if USER_CHECK_ENABLED(TEMPERATURE)
        if(temp_value == 0) temp_value = xapp_temperature_get_average();
        #else 
        if(temp_value == 0) temp_value = 34.0;
        #endif 
        if( temp_value == 0 || had_report_touch_state == false)
        {
            widgets[2].visible = 0;
            widgets[3].visible = 1;
        }
        else 
        {
            widgets[2].visible = 1;
            widgets[3].visible = 0;
            prop.numberlist.value[0] = temp_value;
            prop.numberlist.value[1] = (uint8_t)((long)(temp_value*10)%10);
            prop.numberlist.cnt = 2;
            gui_widget_update_prop( &widgets[2], &prop );
        }
    }
    
    if(xapp_loacl_is_chinese_language())
    {
        widgets[5].visible = 1;
        prop.digital.idx = 2;
        gui_widget_update_prop( &widgets[5], &prop );
    }
    else
    {
        widgets[5].visible = 0;
    }
    
//    //last data
//    {
//        uint16_t len=0;
//        string_t const *pstr = xapp_local_text_item_get( TEXT_TAG_LATEST_MEASURE );
//        if( pstr != NULL && ((pstr->len + len) <= sizeof(share_text)/sizeof(share_text[0])))
//        {
//            memcpy(share_text+len,(void*)pstr->text,pstr->len*sizeof(uint16_t));
//            len += pstr->len;
//        }
//        
//        //增加空格
//        if(len +1 <= sizeof(share_text)/sizeof(share_text[0]))
//        {
//            share_text[len] = ' ';len++;
//        }
//        
//        #if USER_CHECK_ENABLED(TEMPERATURE)
//        float average = xapp_temperature_get_desc()->degree.average_indeed;
//        #else 
//        float average = 88.8;
//        #endif
//        
//        //增加百位
//        if(len +1 <= sizeof(share_text)/sizeof(share_text[0]) && (long)average/100 != 0)
//        {
//            share_text[len] = '0'+average/100;len++;
//        }
//        
//        //增加十位
//        if(len +1 <= sizeof(share_text)/sizeof(share_text[0]) && ((long)average/100 != 0 || ((long)average/10)%10 !=0))
//        {
//            share_text[len] = '0'+((long)average/10)%10;len++;
//        }
//        
//        //增加个位
//        if(len +1 <= sizeof(share_text)/sizeof(share_text[0]))
//        {
//            share_text[len] = '0'+(long)average%10;len++;
//        }
//        
//        //增加.
//        if(len +1 <= sizeof(share_text)/sizeof(share_text[0]))
//        {
//            share_text[len] = '.';len++;
//        }
//        
//        //增加一位小数
//        if(len +1 <= sizeof(share_text)/sizeof(share_text[0]))
//        {
//            share_text[len] = '0'+(long)(average*10)%10;len++;
//        }
//        
//        prop.text.context = (void*)share_text;
//        prop.text.len = len;
//        gui_widget_update_prop( &widgets[5], &prop );
//        widgets[5].visible = 0;
//    }
                
    FLAG_CLEAR();
}

/* 刷新显示回调
   根据当前状态，重新绘制指定的控件组 
*/
static int display_refresh_func(gui_menu_t * menu)
{
    return 1;
}

static void on_touch(void* pvParameters, gui_menu_t * menu)
{
    tp_algo_evt_t* touch = (tp_algo_evt_t*)pvParameters;

    switch( touch->type )
    {        
        case TP_ALGO_EVT_TYPE_DRAG_X:
        VALUES_SET( x, touch->deltaX );
        local_view_event_handler( tagTEMPDragStart );
        break;

        case TP_ALGO_EVT_TYPE_SLIDE_L:
        local_view_event_handler( tagTEMPToLeft );
        break;;

        case TP_ALGO_EVT_TYPE_SLIDE_R:
        local_view_event_handler( tagTEMPToRight );
        break;
        
        default:
        break;
    }
}
/* 界面的按键处理

*/
static void on_button(void* pvParameters, gui_menu_t * menu)
{
    kb_evt_t* kb = (kb_evt_t*)pvParameters;
    if( kb->type == KB_EVT_CLICK )
    {
        local_view_event_handler( tagTEMPBack );
    }
}

/* 界面的自定义输入事件处理

*/
static void on_event_update(void * pvParameters, gui_menu_t * menu)
{
    custom_evt_t* custom = (custom_evt_t*)pvParameters;
    switch( custom->type )
    {
        case CUSTOM_EVT_TYPE_TEMPERATURE_UPDATE:
        gui_update_event();        
        break;

        case CUSTOM_EVT_TYPE_TEMPERATURE_MEASURE_DONE:
        {
            gui_part_stop();
            gui_core_lifetime_update( menu, 5000 ); 
        }
        break;

        case CUSTOM_EVT_TYPE_WEAR_REMOVE:
        case CUSTOM_EVT_TYPE_WEAR_DETECTED:
        had_report_touch_state=true;
        break;

        default:
        break;
    }
}

/* 界面的触摸事件
   tag 是生效的控件id, 用户根据生效的tag判断是哪个控件点击了，进行处理
*/
static void local_view_event_handler( uint32_t tag )
{
    
    const gui_view_t* cur_wf=&viewApp_Temperature;
    const gui_view_t* next_wf=&viewApp_Sleep;
    const gui_view_t* prev_wf=&viewApp_SPO2;
    
    #if USER_CHECK_ENABLED(TEMPERATURE)
    xapp_temperature_stop_by( TEMP_STOP_SRC_VIEW );
    #endif 
    
    switch( tag )
    {
        case tagTEMPDragStart:
        {
            // 有父级界面，禁止拖动显示
            if( p_this_parent != NULL )
            {
                break;
            }
            int16_t deltaX = VALUES_GET( x );
            if( deltaX > 0 )
            {
                gui_view_create_transition( cur_wf, prev_wf, &manageTransition, deltaX, 0 );
            }
            else 
            {
                gui_view_create_transition( cur_wf, next_wf, &manageTransition, deltaX, 0 );
            }
        }
        break;

        case tagTEMPToLeft:
        if( p_this_parent != NULL )
        {
            break;
        }
        GUI_VIEW_CREATE_NAVIGATE_TO_LEFT( cur_wf, next_wf, 0 );
        break;

        case tagTEMPToRight:
        {
            if( p_this_parent != NULL )
            {
                gui_view_create_return( p_this_parent );
                p_this_parent = NULL;
                break;
            }
             
            GUI_VIEW_CREATE_NAVIGATE_TO_RIGHT( cur_wf, prev_wf, 0 );            
        }
        break;

        case tagTEMPBack: // 返回
        if( p_this_parent != NULL )
        {
            gui_view_create_return( p_this_parent );
            p_this_parent = NULL;
        }
        else 
        {
            gui_view_create( views_load_current_watchface() ); // 返回表盘
        }
        break;;
    }
}
